#!/bin/bash

# 后端部署脚本

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# 获取项目根目录
PROJECT_ROOT="$( cd "$SCRIPT_DIR/../.." && pwd )"
# 后端目录
BACKEND_DIR="$PROJECT_ROOT/video2text-backend"

echo "开始后端部署检查..."
echo "项目根目录: $PROJECT_ROOT"
echo "后端目录: $BACKEND_DIR"

# 检查conda环境
if conda env list | grep -q "video2text"; then
    echo "video2text环境已存在"
    eval "$(conda shell.bash hook)"
    conda activate video2text || exit 1
else
    echo "创建conda环境..."
    conda create -n video2text python=3.10 -y || exit 1
    eval "$(conda shell.bash hook)"
    conda activate video2text || exit 1
fi

# 检查工作目录
if [ ! -d "$BACKEND_DIR" ]; then
    echo "错误: 未找到后端目录: $BACKEND_DIR"
    exit 1
fi

cd "$BACKEND_DIR"

# 检查依赖文件
if [ ! -f "requirements.txt" ]; then
    echo "错误: 未找到requirements.txt"
    exit 1
fi

# 检查依赖更新
echo "检查依赖更新..."
if [ ! -f ".dep_checksum" ] || \
   [ "$(md5sum requirements.txt | cut -d' ' -f1)" != "$(cat .dep_checksum 2>/dev/null)" ]; then
    echo "安装/更新依赖..."
    pip install -r requirements.txt || exit 1
    md5sum requirements.txt | cut -d' ' -f1 > .dep_checksum
else
    echo "依赖已是最新"
fi

# 检查并创建必要目录
for dir in logs temp; do
    if [ ! -d "$dir" ]; then
        echo "创建${dir}目录..."
        mkdir -p "$dir"
    fi
done

# 检查Ollama配置
if [ ! -f "$SCRIPT_DIR/setup_ollama.sh" ]; then
    echo "错误: 未找到setup_ollama.sh"
    exit 1
fi

# 确保setup_ollama.sh可执行
chmod +x "$SCRIPT_DIR/setup_ollama.sh"

# 运行Ollama配置
echo "检查Ollama环境..."
"$SCRIPT_DIR/setup_ollama.sh"

# 检查服务配置
if [ ! -f "app/main.py" ]; then
    echo "错误: 未找到app/main.py"
    exit 1
fi

# 检查是否已有服务运行
if lsof -i:8000 > /dev/null 2>&1; then
    echo "端口8000已被占用，尝试停止现有服务..."
    pid=$(lsof -t -i:8000)
    if [ ! -z "$pid" ]; then
        kill $pid
        sleep 2
    fi
fi

# 启动服务
echo "启动后端服务..."
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload &

# 等待服务启动
echo "等待服务启动..."
for i in {1..30}; do
    if curl -s http://localhost:8000/api/v1/health > /dev/null; then
        echo "服务启动成功!"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "错误: 服务启动超时"
        exit 1
    fi
    sleep 1
done

echo "后端部署完成!"

# 显示部署状态
echo "-------------------"
echo "部署信息:"
echo "- Python版本: $(python --version)"
echo "- Conda环境: video2text"
echo "- pip版本: $(pip --version)"
echo "- 服务地址: http://localhost:8000"
echo "- 日志目录: $(pwd)/logs"
echo "-------------------" 